package com.um.jdy.platform.shop.manager;

import com.um.jdy.common.shop.entity.dto.GoodsOptionDTO;
import com.um.jdy.common.shop.entity.po.GoodsOption;
import com.um.jdy.common.shop.entity.po.GoodsSpec;
import com.um.jdy.common.shop.entity.po.GoodsSpecItem;
import com.um.jdy.common.shop.service.GoodsOptionService;
import com.um.jdy.common.shop.service.GoodsService;
import com.um.jdy.common.shop.entity.po.Goods;
import com.um.jdy.common.shop.entity.dto.GoodsDTO;
import com.um.jdy.common.shop.entity.vo.GoodsVO;
import com.um.jdy.common.shop.service.GoodsSpecItemService;
import com.um.jdy.common.shop.service.GoodsSpecService;
import com.um.jdy.platform.shop.entity.dto.GoodsListDTO;
import com.um.jdy.platform.shop.entity.dto.GoodsPageDTO;
import com.um.jdy.platform.shop.entity.dto.GoodsSaveDTO;
import com.um.jdy.platform.shop.entity.vo.GoodsPageVO;
import com.um.springboot.starter.config.SystemSQL;
import com.um.springboot.starter.dao.BaseDao;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BasePlusManager;
import com.um.springboot.starter.orm.params.ListDTO;
import com.um.springboot.starter.orm.params.PageDTO;
import com.um.springboot.starter.utils.DateUtil;
import com.um.springboot.starter.utils.JSONUtil;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 管理类：商品表
 */
@Component
@Transactional
public class GoodsManager extends BasePlusManager<GoodsService, Goods, GoodsDTO, GoodsVO, GoodsPageDTO, GoodsListDTO> {

    @Autowired
    BaseDao baseDao;

    @Autowired
    GoodsOptionService goodsOptionService;

    @Autowired
    GoodsSpecService goodsSpecService;

    @Autowired
    GoodsSpecItemService goodsSpecItemService;

    public Page<GoodsPageVO> getGoodsPage(GoodsPageDTO goodsDTO) {
        Page<GoodsPageVO> page = new Page<>();
        page.setPageNo(goodsDTO.getPageNo());
        page.setPageSize(goodsDTO.getPageSize());

        String bigCode = StringUtil.getTrim(goodsDTO.getBigCode(), "%");
        String code = StringUtil.getTrim(goodsDTO.getCode(), "%");
        String goodsName = StringUtil.getTrim(goodsDTO.getShopGoodsName(), "%");
        String isUpper = StringUtil.getTrim(goodsDTO.getIsUpper());

        String sortName = StringUtil.getTrim(goodsDTO.getSortName());
        String sortType = StringUtil.getTrim(goodsDTO.getSortType());
        String stockType = StringUtil.getTrim(goodsDTO.getStockType());

        String custom = "";

        if (stockType.equals("0")) {//出售中
            custom = "stock.balance_stock > 0 and g.is_upper = 'Yes'";
        } else if (stockType.equals("1")) {//低库存
            custom = "stock.balance_stock > 0 and stock.balance_stock < 10 and g.is_upper = 'Yes'";
        } else if (stockType.equals("2")) {//已售罄
            custom = "stock.balance_stock = 0 and g.is_upper = 'Yes'";
        } else if (stockType.equals("3")) {//已下架
            custom = "g.is_upper = 'No'";
        } else if (!isUpper.isEmpty()) {//上下架状态
            custom = "g.is_upper like '" + isUpper + "'";
        } else {
            custom = "1=1";
        }

        String sql = SystemSQL.getInstance().getSystemSQL("get_goods_page");
        sql = sql.replace("[orderby]", sortName + " " + sortType);
        sql = sql.replace("[custom]", custom);

        String sumSql = SystemSQL.getInstance().getSystemSQL("get_goods_count");
        sumSql = sumSql.replace("[custom]", custom);

        page = service.getViewModelPageBySql(page, sql, sumSql, GoodsPageVO.class, new Object[]{getComId(),bigCode, code, goodsName});
        return page;
    }

    public boolean saveGoods(GoodsSaveDTO goodsDTO) {

        GoodsDTO dtoGoods = goodsDTO.getGoods();
        List<GoodsOptionDTO> skuItems = goodsDTO.getSkuItems();

        if (StringUtil.getTrim(dtoGoods.getShopGoodsId()).isEmpty()) {
            String prefix = DateUtil.getDateString(new Date(), "yyyyMMddhhmmss");
            String goodsCode = baseDao.getMaxCode("shop_goods", "goods_code", "goods_code", prefix, 4);
            dtoGoods.setGoodsCode(goodsCode);
        }

        Goods goods = UMBeanUtils.copyBean(dtoGoods, Goods.class);
        if (goods.getCreateDate() == null) {
            goods.setCreateDate(new Date());
        }
        service.save(goods);

        String goodsId = StringUtil.getTrim(goods.getShopGoodsId());
        List<GoodsOption> oldSkuList = goodsOptionService.getList("shop_goods_id", goodsId);

        //保存多规格库存价格列表
        for (GoodsOptionDTO skuItem : skuItems) {
            String title = StringUtil.getTrim(skuItem.getTitle());

            GoodsOption goodsOption = goodsOptionService.getEntity(new String[]{"shop_goods_id", "title"}, new String[]{goodsId, title});
            if (goodsOption != null) {
                goodsOption.setCostPrice(null);
                goodsOption.setCost(null);

                goodsOption.setThumb(skuItem.getThumb());
                goodsOption.setStock(skuItem.getStock());
                goodsOption.setPrice(skuItem.getPrice());
                goodsOption.setCommission(skuItem.getCommission());
                goodsOption.setVipPrice(skuItem.getVipPrice());
                goodsOption.setSkuCode(skuItem.getSkuCode());

                goodsOptionService.save(goodsOption);

            } else {
                skuItem.setShopGoodsId(goodsId);
                goodsOptionService.save(UMBeanUtils.copyBean(skuItem, GoodsOption.class));
            }

        }

        //删除多规格库存
        for (GoodsOption option : oldSkuList) {
            String title = StringUtil.getTrim(option.getTitle());
            boolean isFind = false;

            for (GoodsOptionDTO skuItem : skuItems) {
                if (title.equals(skuItem.getTitle())) {
                    isFind = true;
                    break;
                }
            }
            //没有找到，则删除
            if (!isFind) {
                goodsOptionService.deleteTrue("shop_goods_option_id", StringUtil.getTrim(option.getShopGoodsOptionId()));
            }

        }

        if ("Yes".equals(StringUtil.getTrim(goods.getIsMoreSpec()))) {

            //保存规则库
            List<Map> options = JSONUtil.parseJSONToList(goods.getOptions() + "");
            for (Map option : options) {

                String title = StringUtil.getTrim(option.get("title"));

                GoodsSpec goodsSpec = goodsSpecService.getEntity("title", title);
                if (goodsSpec == null) {
                    goodsSpec = new GoodsSpec();
                    goodsSpec.setTitle(title);
                } else {
                    goodsSpec.setUseCount(Integer.parseInt(StringUtil.getTrim(goodsSpec.getUseCount())) + 1);
                }

                goodsSpecService.save(goodsSpec);

                //保存二级规格
                List<Map> subOptions = JSONUtil.parseJSONToList(option.get("items") + "");
                if (subOptions != null && subOptions.size() > 0) {
                    int count = 0;
                    for (Map subOption : subOptions) {

                        String subTitle = StringUtil.getTrim(subOption.get("title"));

                        GoodsSpecItem specItem = goodsSpecItemService.getEntity(new String[]{"title", "sub_title"}, new String[]{title, subTitle});

                        if (specItem == null) {
                            specItem = new GoodsSpecItem();
                            specItem.setTitle(title);
                            specItem.setSubTitle(subTitle);
                        }
                        specItem.setSortNo(count);
                        goodsSpecItemService.save(specItem);
                        count++;

                    }
                }

            }

        }

        return true;
    }

    public Response changeStatus(String id, String status) {
        Goods goods = service.getEntity(id);
        if (goods == null)
            return Response.failed("商品不存在");
        goods.setIsUpper(status);
        return service.update(goods) ? Response.success() : Response.failed("更新失败");
    }

}
